package corejava;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;

/**
 * Created by lemontree on 2017/4/27.
 */
public class ObjectAnalyzerTest {
    private static ArrayList<Object> visited = new ArrayList<Object>();

    public static void main(String[] args) {
        ArrayList<String> str = new ArrayList<String>();
        str.add("ssss");
        System.out.println(toString(str));
        System.out.println(toString(str));
        System.out.println(toString(str));
        System.out.println(toString(str));
    }

    public static String toString(Object obj) {
        if (obj == null) {
            return null;
        }
        if (visited.contains(obj)) {
            return "...";
        }
        visited.add(obj);
        Class cl = obj.getClass();
        if (cl == String.class) return (String) obj;
        if (cl.isArray()) {
            String r = cl.getComponentType() + "[]{";
            for (int i = 0; i < Array.getLength(obj); i++) {
                if (i > 0) {
                    r += ",";
                }
                Object val = Array.get(obj, i);
                if (cl.getComponentType().isPrimitive()) {
                    r += val;
                } else {
                    r += toString(val);
                }
            }
            return r += "}";
        }
        String r = cl.getName();
        do {
            r += "[";
            Field[] files = cl.getDeclaredFields();
            AccessibleObject.setAccessible(files, true);
            for (Field field : files) {
                if (!Modifier.isStatic(field.getModifiers())) {
                    if (r.endsWith("[")) {
                        r += ",";
                    }
                    r += field.getName() + "=";
                    try {
                        Class t = field.getType();
                        Object val = field.get(obj);
                        if (t.isPrimitive()) {
                            r += val;
                        } else {
                            r += toString(val);
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
            r += "]";
            cl = cl.getSuperclass();
        } while (cl != null);
        return r;
    }
}
